package cn.com.startai.smartadh5.main.activity;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.orhanobut.logger.Logger;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xwalk.core.XWalkInitializer;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.startai.smartadh5.R;
import cn.com.startai.smartadh5.datasourceupdate.DataSourceUpdateModule;
import cn.com.startai.smartadh5.datasourceupdate.entity.TaskPush;
import cn.com.startai.smartadh5.db.db.entity.BroadcastTable;
import cn.com.startai.smartadh5.db.db.entity.PlayInfo;
import cn.com.startai.smartadh5.db.db.entity.Screen;
import cn.com.startai.smartadh5.db.db.manager.BroadcastTableHelper;
import cn.com.startai.smartadh5.db.db.manager.PlayInfoHelper;
import cn.com.startai.smartadh5.db.db.manager.ScreenHelper;
import cn.com.startai.smartadh5.db.sp.SPManager;
import cn.com.startai.smartadh5.extension.config.Config;
import cn.com.startai.smartadh5.extension.utils.LogUtil;
import cn.com.startai.smartadh5.extension.utils.SmartTimerService;
import cn.com.startai.smartadh5.hotcodeupdate.entity.HotInMsg;
import cn.com.startai.smartadh5.locallog.SmartLocalLog;
import cn.com.startai.smartadh5.locallog.SmartToast;
import cn.com.startai.smartadh5.locallog.entity.LogMsg;
import cn.com.startai.smartadh5.main.adapter.ViewPagerAdapter;
import cn.com.startai.smartadh5.main.application.Application;
import cn.com.startai.smartadh5.main.base.activity.BaseActivityV1;
import cn.com.startai.smartadh5.main.fragment.BaseFragment;
import cn.com.startai.smartadh5.main.fragment.DefaultFragment;
import cn.com.startai.smartadh5.main.fragment.ImageFragment;
import cn.com.startai.smartadh5.main.fragment.MusicFragment;
import cn.com.startai.smartadh5.main.fragment.VideoFragment;
import cn.com.startai.smartadh5.main.fragment.WebFragment;
import cn.com.startai.smartadh5.main.view.VerticalViewPager;
import cn.com.startai.smartadh5.pluginmanager.server.PluginServer;
import cn.com.startai.smartadh5.processlogic.entity.bean.BroadcastTableDeleteBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.HardwareKey;
import cn.com.startai.smartadh5.processlogic.entity.bean.ShowFileTypeBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.StatusBarBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayListData;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.RemovePlayListBean;
import cn.com.startai.smartadh5.processlogic.entity.event.OnCommand;
import cn.com.startai.smartadh5.processlogic.entity.event.OnScreenshot;
import cn.com.startai.smartadh5.processlogic.entity.event.OnTextPlayer;
import cn.com.startai.smartadh5.processlogic.entity.event.OnTimeoutExecute;
import cn.com.startai.smartadh5.processlogic.entity.event.OnVideoPlayer;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayListEvent;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayLoopModeEvent;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayModeChangedEvent;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayStateChangeEvent;
import cn.com.startai.smartadh5.processlogic.entity.event.player.RemovePlayListEvent;
import cn.startai.apkcommunicate.CommunicateType;
import cn.startai.apkcommunicate.StartaiCommunicate;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * 主 Activity
 */
public class IndexActivity extends BaseActivityV1 implements XWalkInitializer.XWalkInitListener {


    private String TAG = this.getClass().getSimpleName();

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, IndexActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.verticalViewPager)
    VerticalViewPager mViewPager;
    private ViewPagerAdapter mViewPagerAdapter;
    private List<BaseFragment> mFragments;

    private DefaultFragment mDefaultFragment;
    private WebFragment mWebFragment;
    private VideoFragment mVideoFragment;
    private MusicFragment mMusicFragment;
    private ImageFragment mImageFragment;

    private int fixedPager;
    private static boolean isBtStop = false;
    private int defaultPlayMode = 0;


    @Override
    protected boolean shouldInterceptBack() {
        SPUtils.getInstance().put("NextNumber", 1);
        return true;
    }

    @Override
    protected int getLayoutId() {
        if (SPManager.getInstance().isMusicBox()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        return R.layout.activity_index;
    }


    @Override
    public void initData() {
        Logger.i("执行oncreate");
        if (Config.screenOff) {
            isBtStop = true;
        }

        defaultPlayMode = SPManager.getInstance().getCurrentPlayerMode();

        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        if (SPManager.getManager().getBoolean(SPManager.KEY_APP_USE_CROSSWALK, false)) {
            new XWalkInitializer(this, this).initAsync();
        } else {
            initFragments();
            Logger.i("已经初始化fragment");
        }

        // SmartAD Loaded
        PluginServer.sendHostLoaded();


        SPUtils.getInstance().put("getFragmentPos", 5);

    }

    @Override
    public void initView() {

    }

    @Override
    public void addViewListener() {
    }


    private void initFragments() {
        mFragments = new ArrayList<>();
        mWebFragment = new WebFragment();

        mWebFragment.setRetainInstance(true);

        mDefaultFragment = new DefaultFragment();
        mFragments.add(mDefaultFragment);

        //设置渲染方式为 SurfaceView
//        GSYVideoType.setRenderType(GSYVideoType.GLSURFACE);

        //设置开启 精准进度条
        VideoOptionModel videoOptionModel1 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);


        List<VideoOptionModel> list = new ArrayList<>();
        //如果为音响
        if (SPManager.getInstance().isMusicBox()) {
            list.add(videoOptionModel1);

            //开启硬解码
            GSYVideoType.enableMediaCodec();
            GSYVideoType.enableMediaCodecTexture();
            mVideoFragment = new VideoFragment();
            mMusicFragment = new MusicFragment();
            mImageFragment = new ImageFragment();
            mFragments.add(mVideoFragment);
            mFragments.add(mMusicFragment);
            mFragments.add(mImageFragment);
            mFragments.add(mWebFragment);
            GSYVideoManager.instance().setOptionModelList(list);
        } else {
            GSYVideoType.enableMediaCodec();
            GSYVideoType.enableMediaCodecTexture();
            //广告屏
            mFragments.add(mWebFragment);
        }
//        GSYVideoManager.instance().setOptionModelList(list);


        mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                LogUtil.v("indexActivity", "position = " + position);

            }

            @Override
            public void onPageSelected(int position) {
                Log.i("indexActivity", "position=" + position);
//                if(position==0){
//                    SPUtils.getInstance().put("getindex",position);
//
//                }else if (position==1){
//                    SPUtils.getInstance().put("getindex",position);
//                }else if(position==2){
//                    SPUtils.getInstance().put("getindex",position);
//                }else if(position==3){
//                    SPUtils.getInstance().put("getindex",position);
//                }else if (position==4){
//                    SPUtils.getInstance().put("getindex",position);
//                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setAdapter(mViewPagerAdapter);
        mViewPager.setOffscreenPageLimit(mFragments.size());


        fixedPager = SPManager.getManager().getInt(SPManager.KEY_FIXED_VIEWPAGER_INDEX, -1);

        if (!SPManager.getInstance().isMusicBox()) {
            if (fixedPager != -1) {
                mViewPager.setCurrentItem(fixedPager);
            } else {
                mViewPager.setCurrentItem(0);
            }
        }
    }

    public VerticalViewPager getVerticalViewPager() {
        return mViewPager;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name)) {
                    return getApplicationContext().getSystemService(name);
                }
                return super.getSystemService(name);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logger.i("执行onResume");
        PluginServer.sendServerPause(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Logger.i("执行onPause");
        PluginServer.sendServerPause(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTaskPush(TaskPush taskPush) {

        LogUtil.d("live", "  indexActivity onTaskPush ");

        doTaskPush(taskPush);
        Logger.i("onTaskPush");
    }

    //    private boolean isFirst = false;
    public void doTaskPush(TaskPush taskPush) {

        int index = mFragments.indexOf(mWebFragment);

        if (!Config.screenOff && mViewPager.getCurrentItem() != index) {
            if (fixedPager == -1) {
                mViewPager.setCurrentItem(index);
            }
        }
        // 有向 WebFragment 推送的播表消息
        if (mWebFragment != null) {
            // record
            LogMsg logMsg = new LogMsg(LogMsg.TYPE_SEND, "Native", "HTML", "向前端推送播表消息");
            // record remarks
            ArrayList<String> remarks = new ArrayList<>();
            StringBuilder remark = new StringBuilder();
            // 延迟推送的消息
            if (taskPush.isDelay()) {

                LogUtil.d("live", "  indexActivity delayToPush() ");

                remark.append("是否延迟推送: 是\n");
                remark.append("当前屏幕状态：").append(Config.screenOff ? "关屏" : "开屏").append("\n");
                remark.append("延迟推送时间: ");
                remark.append(TimeUtils.date2String(taskPush.getDate())).append("\n");
                remark.append("\n推送消息: ");
                remark.append(taskPush.getMessage());
                remarks.add(remark.toString());

                delayToPush(taskPush);

            } else {

                LogUtil.d("live", "  indexActivity pushToWeb() ");

                remark.append("是否延迟推送: 否\n");
                remark.append("当前屏幕状态：").append(Config.screenOff ? "关屏" : "开屏");
                remark.append("\n推送消息: ");
                remark.append(taskPush.getMessage());
                remarks.add(remark.toString());
                Logger.i("doTaskPush的pushToWeb执行");
                pushToWeb(taskPush);
            }

            logMsg.setRemarks(remarks);
            SmartLocalLog.writeLog(logMsg);
        }
    }

    /**
     * 将播表 Screen 推送到 Web 中
     */
    private void pushToWeb(TaskPush taskPush) {
        if (taskPush.isAdd()) {
            long currId = SPManager.getInstance().getCurrentBtId();
            if (currId != taskPush.getTableId()) {
                SPManager.getInstance().saveCurrentBtId(taskPush.getTableId());
                SPManager.getManager().put(SPManager.KEY_CURRENT_BT_PLAY_TIME, System.currentTimeMillis());
            }
        }
//        Logger.i("屏幕开关:"+Config.screenOff);
        if (!Config.screenOff) {
            // 推送到 WebView 页面
            JSONObject messageObj = JSON.parseObject(taskPush.getMessage());
            if (messageObj.getString("datatype").equals("nothing EmptyPage")) {
                //没有播表
                mWebFragment.sendState(4, false);
                mWebFragment.onTaskPush(taskPush.getMessage());
                Logger.i("没有播表...");
                return;
            }
            if (checkSpots(messageObj)) {
                //播放
                mWebFragment.sendState(1, false);
                mWebFragment.onTaskPush(taskPush.getMessage());
                operateStatusBar(taskPush.getTimeType(), taskPush.getLogoPath());
                Logger.i("播表播放...");
                Logger.i("推送的消息：" + taskPush.getMessage());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void takeScreenshot(OnScreenshot screenshot) {
        Logger.i("开始截屏");
        // 获取屏幕
        View dView = getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        if (bmp != null) {
            try {
                // 获取内置SD卡路径
                String sdCardPath = SPManager.getInstance().getSdcardPath();
                String imagesPath = sdCardPath + "/startai/images/";
                FileUtils.createOrExistsDir(imagesPath);
                // 图片文件路径
                String filePath = imagesPath + "/screenshot" + "_" + System.currentTimeMillis() + ".png";

                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
                screenshot.setScreenShotPath(filePath);
                StartaiCommunicate.getInstance().send(this.getApplicationContext(),
                        CommunicateType.COMMUNICATE_TYPE_SCREENSHOT,
                        JSON.toJSONString(screenshot));
                Logger.i("截屏成功");
            } catch (Exception e) {
                e.printStackTrace();
                Logger.i("截屏失败");
            }
        }
    }

    //语音指令
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommand(OnCommand command) {
        switch (command.getCmd()) {
            case CommunicateType.COMMUNICATE_TYPE_KEY_BARCODE:
                mViewPager.setCurrentItem(0);
                if (mDefaultFragment != null) {
                    mDefaultFragment.switchPage(1);
                }
                break;
            case CommunicateType.COMMUNICATE_TYPE_KEY_ALARMCLOCK:
            case CommunicateType.COMMUNICATE_TYPE_KEY_PAUSE:
                mViewPager.setCurrentItem(0);
                if (mDefaultFragment != null) {
                    mDefaultFragment.switchPage(0);
                }
                break;
            case CommunicateType.COMMUNICATE_TYPE_KEY_PLAY:
                if (!SPManager.getInstance().isMusicBox()) {
                    if (mViewPager.getCurrentItem() != 1) {
                        mViewPager.setCurrentItem(1);
                    }
                } else {
                    mViewPager.setCurrentItem(SPManager.getInstance().getCurrentPlayerMode());
                }
                break;
            case CommunicateType.COMMUNICATE_TYPE_KEY_RECOGNIZETION_START:
                Intent intent = new Intent(this, VoiceActivity.class);
                startActivity(intent);
                break;
            case CommunicateType.COMMUNICATE_TYPE_KEY_STOP:
                if (!isBtStop) {
                    mViewPager.setCurrentItem(0);
                    mWebFragment.sendState(3);
                    LogUtil.v("indexAcitvity", "index 得sendstate执行了");
                    isBtStop = true;
                }
                break;
            case CommunicateType.COMMUNICATE_TYPE_KEY_REPLAY:
                DataSourceUpdateModule.playBtById("-1");
                break;
        }
    }

    public static boolean isBtStop() {
        return isBtStop;
    }

    public static void setBtStop(boolean b) {
        isBtStop = b;
    }

    public void delayToPush(TaskPush taskPush) {
        SmartTimerService.getInstance().startTask(taskPush.getScreenId(), taskPush.getDate(), () -> {
            if (System.currentTimeMillis() > taskPush.getDate().getTime()) {
                this.runOnUiThread(() ->
                        pushToWeb(taskPush)
                );
                //当任务执行完成后停止任务
                SmartTimerService.getInstance().stopTask(taskPush.getScreenId());
            }
        });
    }

    private boolean checkSpots(JSONObject messageObj) {
        // 检测播表是否是插播播表, 返回true不阻止推送到html, 返回false阻止
        Logger.i("推送Screen -> html: " + messageObj);

        JSONObject screen = messageObj.getJSONObject("screen");

        if (screen != null) {
            String sid = screen.getString("sid");
            String utype = screen.getString("utype");
            if (sid.equals("sid_0") && utype.equals("2")) {
                Logger.e("播表属于插播");
                boolean isMusicBox = SPManager.getInstance().isMusicBox();
                if (isMusicBox) {
                    // 音箱

                } else {
                    // 其他

                }
                return false;
            } else if (utype.equals("2")) {
                return false;
            }

            if (!SPManager.getInstance().isMusicBox()) {
                int syncType = SPManager.getInstance().getSyncType();
                if (syncType == 0) {
                    // 每小时同步
                    Integer totalLength = screen.getInteger("totalLength"); // 总时间
                    int timeInterval = totalLength == null ? 1 : totalLength / 3600 + 1; // 时间间隔
                    String schedulingPattern = "0 */" + timeInterval + " * * *";
                    SmartTimerService.getInstance().startTask("每小时同步", schedulingPattern,
                            new HourSyncTask(timeInterval));
                } else {
//                    // 绝对时间同步, 计算时间线
//                    Integer totalLength = screen.getInteger("totalLength");
//                    if (totalLength != null) {
//                        long start = screen.getLongValue("start");
//                        countTimeLineToPushTask(totalLength, start);
//                    }
                    //不同步
                }
            }
        }

        return true;
    }

    /**
     * 每小时同步任务
     */
    private class HourSyncTask implements Runnable {

        private int timeInterval;//时间间隔

        public HourSyncTask(int timeInterval) {
            this.timeInterval = timeInterval;
        }

        @Override
        public void run() {
            IndexActivity.this.runOnUiThread(() -> {
                if (!Config.screenOff && !ScreenHelper.getInstance().hasBroadWillPlay()) {
                    ArrayList<String> remarks = new ArrayList<>();
                    remarks.add("播表同步间隔时间：" + timeInterval + "小时");
                    SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_HANDLER, "Native",
                            "Native", "播表同步开始", remarks));
                    DataSourceUpdateModule.playBtById("-1");
                }
            });
        }
    }

    private void countTimeLineToPushTask(Integer totalLength, long start) {
        int splitLength = 0;
        if (totalLength > 60) {
            splitLength = totalLength;
        } else {
            splitLength = 60 / totalLength * totalLength;
        }
        splitLength = splitLength * 1000;

        try {
//            long startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).parse(start).getTime();
            long startTime = start;
            long currentTime = System.currentTimeMillis();
            if (startTime + splitLength < currentTime) {
                startTime = (currentTime - startTime) / splitLength * splitLength + startTime + splitLength;
            } else {
                startTime += splitLength;
            }

            // 开启定时刷新
            doWhileTaskPush(startTime, splitLength);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.e("转换时间出错, 绝对时间同步出错!");
        }
    }

    public void doWhileTaskPush(long startTime, long splitLength) {
        // 记录日志
        ArrayList<String> remarks = new ArrayList<>();
        remarks.add("下一个自动刷新时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date(startTime)));
        SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_HANDLER, "Native", "Native", "绝对时间同步开启", remarks));

        SmartTimerService.getInstance().startTask("绝对时间同步", new Date(startTime), () -> {
            this.runOnUiThread(() -> {
                DataSourceUpdateModule.doTaskPush(false);
                // 执行任务结束后, 执行下一个时间点
                doWhileTaskPush(startTime + splitLength, splitLength);
            });
        });
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void callAllView(CancelAllViewEvent event){
//        if (mWebFragment != null) {
//            mWebFragment.cancelAllView();
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoPalyer(OnVideoPlayer onVideoPlayer) {
        ArrayList<String> remark = new ArrayList<>();
        if (onVideoPlayer.getCancelIntent() != null && onVideoPlayer.getCancelIntent()) {
            // cancel video
            Logger.i("H5请求原生取消播放视频! videoId: " + onVideoPlayer.getVideoId() + " path: " + onVideoPlayer.getPath());
            remark.add("屏幕状态：" + (Config.screenOff ? "关屏" : "开屏"));
            remark.add("取消播放视频!");

            if (mWebFragment != null) {
                mWebFragment.onCancelVideo(onVideoPlayer.getVideoId(), true);
            }
        } else {

            remark.add("屏幕状态：" + (Config.screenOff ? "关屏" : "开屏"));
            remark.add("path: " + onVideoPlayer.getPath());

            if (!Config.screenOff) {
                remark.add("播放视频! ");
                Logger.i("H5请求原生播放视频! videoId: " + onVideoPlayer.getVideoId());
                if (mWebFragment != null) {
                    mWebFragment.onPlayVideo(onVideoPlayer);
                }
            } else {
                remark.add("屏幕关闭，不播放视频 ");
            }
        }

        SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "HTML", "Native"
                , "H5请求原生视频操作!", remark));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTextPlayer(OnTextPlayer onTextPlayer) {
        if (onTextPlayer.getCancelIntent() != null && onTextPlayer.getCancelIntent()) {
            // cancel text
            Logger.i("H5请求原生取消文字跑马灯！");

            if (mWebFragment != null) {
                mWebFragment.onCancelText(onTextPlayer.getTextId(), true);
                SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "HTML", "Native"
                        , "H5请求原生取消文字跑马灯!"));
            }
        } else {
            // play text
            Logger.i("H5请求原生文字跑马灯！textContext: " + onTextPlayer.getContent());
            if (mWebFragment != null) {
                mWebFragment.onPlayText(onTextPlayer);
                SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "HTML", "Native"
                        , "H5请求原生文字跑马灯!"));

                //记录跑马灯日志
                ArrayList<String> remarks = new ArrayList<>();
                remarks.add("跑马灯内容： " + Html.fromHtml(onTextPlayer.getContent()).toString());
                SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "HTML", "Native"
                        , "H5请求原生文字跑马灯!", remarks));
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeoutExecute(OnTimeoutExecute execute) {
        if (mWebFragment != null) {
            mWebFragment.onTimeout(execute.getTimeoutKey());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHotInFinished(HotInMsg hotInMsg) {
        if (mWebFragment != null) {
            mWebFragment.reload();
        }
    }

    //按键指令
    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHardwareKeyPress(HardwareKey hardwareKey) {
        if (!isForeground) {
            return;
        }
        int currentItem = mViewPager.getCurrentItem();
        int itemSize = mFragments.size();
        Log.d(TAG, "COMMUNICATE_TYPE_MEDIA_PLAYLIST_CHANGE    currentItem ==> " + currentItem);

        if (hardwareKey.getDirection() == CommunicateType.COMMUNICATE_TYPE_KEY_ACTION_DOWN
                && currentItem > 0) {
            if (fixedPager != -1) {
                SmartToast.error("标签页已经固定, 无法切换!");
            } else {
                mViewPager.setCurrentItem(currentItem - 1);
                EventBus.getDefault().postSticky(new PlayModeChangedEvent(currentItem - 1));
            }
        }

        if (hardwareKey.getDirection() == CommunicateType.COMMUNICATE_TYPE_KEY_ACTION_UP
                && currentItem < (itemSize - 1)) {
            if (fixedPager != -1) {
                SmartToast.error("标签页已经固定, 无法切换!");
            } else {
                mViewPager.setCurrentItem(currentItem + 1);
                EventBus.getDefault().postSticky(new PlayModeChangedEvent(currentItem + 1));
            }

        }

        if (hardwareKey.getDirection() == CommunicateType.COMMUNICATE_TYPE_KEY_ACTION_LEFT) {
            for (BaseFragment mFragment : mFragments) {
                if (mFragment.getVisible()) {
                    mFragment.onLeftPress();
                }
            }
        }

        if (hardwareKey.getDirection() == CommunicateType.COMMUNICATE_TYPE_KEY_ACTION_RIGHT) {
            for (BaseFragment mFragment : mFragments) {
                if (mFragment.getVisible()) {
                    mFragment.onRightPress();
                }
            }
        }
    }

    /**
     * 删除播表
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteBroadTable(BroadcastTableDeleteBean bean) {
        List<BroadcastTable> tables = BroadcastTableHelper.getInstance().queryByBtId(bean.getId());

        //停止延时推送任务
        for (BroadcastTable table : tables) {
            List<Screen> screens = table.getScreens();
            for (Screen screen : screens) {
                SmartTimerService.getInstance().stopTask(String.valueOf(screen.getId()));
                SmartTimerService.getInstance().stopTask(String.valueOf(-screen.getId()));
            }
        }
        BroadcastTableHelper.getInstance().deleteBroadcastTable(tables);
        SmartToast.success("播表删除成功");
        LogMsg logMsg = new LogMsg(LogMsg.TYPE_HANDLER, "Native", "Native", "删除播表id为" + bean.getId() + "的播表");
        SmartLocalLog.writeLog(logMsg);

    }

    /**
     * 播放列表
     *
     * @param event
     */
    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void playList(PlayListEvent event) {
        PlayListData playListData = event.getPlayListData();
        int type = -1;
        switch (playListData.getFileType()) {
            case PlayInfo.STR_TYPE_MUSIC:
                type = PlayInfo.TYPE_MUSIC;
                break;
            case PlayInfo.STR_TYPE_IMAGE:
                type = PlayInfo.TYPE_IMAGE;
                break;
            case PlayInfo.STR_TYPE_VIDEO:
                type = PlayInfo.TYPE_VIDEO;
                break;
        }
        SPManager.getInstance().saveCurrentPlayerMode(type);
        boolean needReplace = playListData.getIsReplace() == 1;
        PlayInfoHelper.getInstance().insertList(playListData.getPlayList(), type, needReplace);
        if (type == PlayInfo.TYPE_VIDEO) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (needReplace) {
                        mVideoFragment.isInit = true;
                        mViewPager.setCurrentItem(mFragments.indexOf(mVideoFragment));
                        mVideoFragment.setUp(playListData.getPlayList());
                        if (isForeground) {
                            mVideoFragment.play();
                        }
                    } else {
                        mVideoFragment.appendPlayList(playListData.getPlayList());
                    }

                }
            });
        } else if (type == PlayInfo.TYPE_MUSIC) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (needReplace) {
                        mMusicFragment.isInit = true;
                        mViewPager.setCurrentItem(mFragments.indexOf(mMusicFragment));
                        mMusicFragment.setUp(playListData.getPlayList());
                        if (isForeground) {
                            mMusicFragment.play(0);
                            Log.i("indexActivity", "播放音乐");
                        }
                    } else {
                        mMusicFragment.appendAudioList(playListData.getPlayList());
                    }

                }
            });
        } else if (type == PlayInfo.TYPE_IMAGE) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (needReplace) {
                        mImageFragment.isInit = true;
                        mViewPager.setCurrentItem(mFragments.indexOf(mImageFragment));
                        mImageFragment.setUp(playListData.getPlayList());
                    } else {
                        mImageFragment.appendPlayList(playListData.getPlayList());
                    }
                }
            });
        }
    }

    /**
     * 改变播放状态
     */
    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changePlayState(PlayStateChangeEvent event) {
        if (mViewPager.getCurrentItem() == mFragments.indexOf(mVideoFragment)) {
            mVideoFragment.changePlayState(event.getBean());

        } else if (mViewPager.getCurrentItem() == mFragments.indexOf(mMusicFragment)) {
            mMusicFragment.changePlayState(event.getBean());
        } else if (mViewPager.getCurrentItem() == mFragments.indexOf(mImageFragment)) {
            mImageFragment.changePlayState(event.getBean());
        }
    }

    /**
     * 删除播放列表
     */
    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void removePlayList(RemovePlayListEvent event) {
        if (event.getBean().getFiles() == null || event.getBean().getFiles().isEmpty()) {
            return;
        }

        int type = PlayInfo.TYPE_VIDEO;
        switch (event.getBean().getFileType()) {
            case PlayInfo.STR_TYPE_MUSIC:
                type = PlayInfo.TYPE_MUSIC;
                break;
            case PlayInfo.STR_TYPE_IMAGE:
                type = PlayInfo.TYPE_IMAGE;
                break;
            case PlayInfo.STR_TYPE_VIDEO:
                type = PlayInfo.TYPE_VIDEO;
                break;
        }
        int removeFileId;
        List<RemovePlayListBean.FileIdsBean> removeList = event.getBean().getFiles();
        if (removeList.size() == 1) {
            //移除单个
            removeFileId = removeList.get(0).getFileId();
            PlayInfoHelper.getInstance().deleteByFileId(removeFileId);
        } else {
            //清空
            removeFileId = -1;
            PlayInfoHelper.getInstance().deleteByType(type);
        }

        if (mViewPager.getCurrentItem() == mFragments.indexOf(mVideoFragment) && type == PlayInfo.TYPE_VIDEO) {
            runOnUiThread(() ->
                    mVideoFragment.removePlayInfo(removeFileId)
            );
        } else if (mViewPager.getCurrentItem() == mFragments.indexOf(mMusicFragment) && type == PlayInfo.TYPE_MUSIC) {
            runOnUiThread(() ->
                    mMusicFragment.removePlayInfo(removeFileId)
            );
        } else if (mViewPager.getCurrentItem() == mFragments.indexOf(mImageFragment) && type == PlayInfo.TYPE_IMAGE) {
            runOnUiThread(() ->
                    mImageFragment.removePlayInfo(removeFileId)
            );
        }
    }

    /**
     * 设置文件list activity的跳转
     **/
    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPagerIdentify(ShowFileTypeBean bean) {
        if (mViewPager.getCurrentItem() == 0) {
            Intent intent = new Intent(IndexActivity.this, PhoneControlActivity.class);
            intent.putExtra("ShowFileTypeBean", bean);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    /**
     * 设置循环模式
     */
    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setPlayLoopMode(PlayLoopModeEvent event) {
        int loopMode = event.getBean().getPlayMode();
        SPManager.getInstance().saveCurrentLoopMode(loopMode);
        if (mViewPager.getCurrentItem() == mFragments.indexOf(mVideoFragment)) {
            mVideoFragment.setPlayMode(loopMode);
        } else if (mViewPager.getCurrentItem() == mFragments.indexOf(mMusicFragment)) {
            mMusicFragment.setLoopMode(loopMode);
        } else if (mViewPager.getCurrentItem() == mFragments.indexOf(mImageFragment)) {
            mImageFragment.setLoopMode(loopMode);
        }
    }


    private StatusBarBean mStatusBarBean;// 用来操作状态栏的的logo和时间的实体类，此处用来避免重复调用方法

    /**
     * 操作状态栏
     */
    private void operateStatusBar(String timeType, String logoPth) {

        StatusBarBean sbean = new StatusBarBean(timeType, logoPth);
        if (!sbean.equals(mStatusBarBean)) {
            mWebFragment.operateTimeView(sbean);
            mWebFragment.operateLogo(sbean);
        }
        mStatusBarBean = sbean;

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return SPManager.getManager().getBoolean(SPManager.KEY_ENABLED_TOUCH_EVENT, false)
                && super.dispatchTouchEvent(ev);
    }


    @Override
    public void onXWalkInitStarted() {

    }

    @Override
    public void onXWalkInitCancelled() {

    }

    @Override
    public void onXWalkInitFailed() {
        SmartToast.error("CrossWalk 加载失败!");
        // CrossWalk 加载失败
        new AlertDialog.Builder(this)
                .setTitle("Error!")
                .setMessage("无法加载CrossWalk, 请检查配置环境!")
                .setCancelable(false)
                .setPositiveButton("确定", null)
                .show();
    }

    @Override
    public void onXWalkInitCompleted() {
        SmartToast.success("CrossWalk 加载成功!");
        // CrossWalk 加载成功 !
        initFragments();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        //检测泄露
        Application.getContext().mRefWatcher.watch(this);

    }
}
